package org.example.RobotModel.generator.Server

import org.example.RobotModel.robotDsl.Device
import org.example.RobotModel.robotDsl.Action

class ServerGen {
	
	static def generateServerRessources(String packageName,Action action) {
		'''
package Server.ServerRessources.«packageName»;
		
import org.restlet.resource.ServerResource;
import org.restlet.resource.Post;
import org.restlet.representation.Representation;

import org.json.JSONException;
import org.json.JSONObject;

/* Resource for one device.
 * 
 */
public class «action.name» extends ServerResource {


    @Post("json")
    public String execute(Representation entity) {
    	try {
    		String req = entity.getText();
    		JSONObject json = new JSONObject(req);
    		
    		«FOR p: action.params»
    			«p.type» «p.name» = («p.type») json.get("«p.name»");
    		«ENDFOR»
    		
    	}catch(Exception e){
			e.printStackTrace();
		}
    	
        return "«action.name»";
    }

}
		'''
		
		
	}
	
	static def generateServerApplication(Iterable<Device> ds) {
		'''
package Server.Application;

import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;

«FOR d : ds»
	import Server.ServerRessources.«d.name».*;
«ENDFOR»



public class RobotApplication extends Application {

    /**
     * Creates a root Restlet that will receive all incoming calls.
     */
    @Override
    public synchronized Restlet createInboundRoot() {
        // Create a router Restlet that routes each call to a
        // new instance of HelloWorldResource.
        Router router = new Router(getContext());

        // Defines routes
     	«FOR d : ds»
     		//Routes for device «d.name»
     		«FOR a : d.actions»
     		router.attach("/«d.name»/«a.name»", Server.ServerRessources.«d.name».«a.name».class);
     		«ENDFOR»
		«ENDFOR»
		
        return router;
        }
	

}
'''

	}

	static def generateServerMain() {
		'''
package Server;

import org.restlet.Component;
import org.restlet.data.Protocol;

import Server.Application.RobotApplication;

public class RobotMain {

    public static void main(String[] args) {
        try {
            // Create a new Component.
            Component component = new Component();

            // Add a new HTTP server listening on port 8182.
            component.getServers().add(Protocol.HTTP, 8182);

            // Attach the sample application.
            component.getDefaultHost().attach(new RobotApplication());

            // Start the component.
            component.start();
        } catch (Exception e) {
            // Something is wrong.
            e.printStackTrace();
        }
    }
}
'''

	}
	
	
	
	
	
}